package com.hui.utils;

import org.springframework.security.crypto.password.PasswordEncoder;

import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ShaPasswordEncoder implements PasswordEncoder {
    private static final String DIGEST_SHA256 = "SHA-256";
    private static MessageDigest sha256;
    static {
        try {
            sha256 = MessageDigest.getInstance(DIGEST_SHA256);
        } catch (NoSuchAlgorithmException e) {
            new IllegalArgumentException("JRE error: Cannot initiate SHA-256 MessageDigest.");
        }
    }
    @Override
    public String encode(CharSequence rawPassword) {
        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        }
        String text = rawPassword.toString();
        return DatatypeConverter.printHexBinary((sha256.digest(text.getBytes())));
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        if (rawPassword == null) {
            throw new IllegalArgumentException("rawPassword cannot be null");
        } else if (encodedPassword != null && encodedPassword.length() != 0) {

            return encodedPassword.equals(
                    DatatypeConverter.printHexBinary(
                            (sha256.digest(rawPassword.toString().getBytes()))));
        } else {
            System.out.println("Empty encoded password");
            return false;
        }
    }


    public static void main(String[] args) {

    }
}

